package org.tong.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.IOException;

/**
 * @author
 * @date 2022-10-09 10:08
 */
public class SensitiveSolve extends JsonSerializer<String> implements ContextualSerializer {

    private Sensitive sensitive;

    public SensitiveSolve() {
    }

    public SensitiveSolve(Sensitive sensitive) {
        this.sensitive = sensitive;
    }

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(sensitive.strategy().getMapper().apply(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        Sensitive annotation = beanProperty.getAnnotation(Sensitive.class);
        if (annotation != null) {
            return new SensitiveSolve(annotation);
        }
        return this;
    }
}
